import { useStore } from 'vuex'
import { ref, computed, watch } from 'vue'
import { getLyric } from '@/service/song'
import Lyric from 'lyric-parser'

export default function useLyric({ songReady, currentTime }) {
  // 当前歌词
  const currentLyric = ref(null)
  // 当前歌词行
  const currentLineNum = ref(0)
  // 没有歌词的时候的初始化
  const pureMusicLyric = ref('')
  // 在圆盘下的歌词显示播放
  const playingLyric = ref('')
  // 获取dom对象
  const lyricScrollRef = ref(null)
  const lyricListRef = ref(null)
  const store = useStore()
  // 获取当前歌曲信息
  const currentSong = computed(() => store.getters.currentSong)

  watch(currentSong, async (newSong) => {
    if (!newSong.url || !newSong.id) {
      return false
    }
    /* 切换歌曲时候, 重置数据 */
    // 歌词停止
    stopLyric()
    // 重置让当前歌词清空，防止两首歌词叠加
    currentLyric.value = null
    // 重置让歌词在第0行
    currentLineNum.value = 0
    // 重置无歌词
    pureMusicLyric.value = ''
    // 重置圆盘下的歌词
    playLyric.value = ''
    const lyric = await getLyric(newSong)
    store.commit('addSongLyric', {
      song: newSong,
      lyric
    })
    // 好好的理解，避免切换歌曲时候导致歌词不一样, 如果不一样，可以直接切到最新的歌曲(在快速切换时会发生)
    // if (currentSong.value.lyric !== lyric) {
    //   return
    // }
    // 解析歌词
    // handleLyric 就是说每次歌词都会一行行的跳，去解析
    currentLyric.value = new Lyric(lyric, handleLyric)
    // 获取每行歌词数组
    const hasLyric = currentLyric.value.lines.length
    // 有歌词
    if (hasLyric) {
      // 保证歌曲在播放时候触发
      if (songReady.value) {
        playLyric()
      }
      // 无歌词
    } else {
      // 一般为轻音乐
      playingLyric.value = pureMusicLyric.value = lyric.replace(
        /\[(\d{2}):(\d{2}):(\d{2})\]/g,
        ''
      )
    }
  })
  // 播放歌词
  function playLyric() {
    const currentLyricVal = currentLyric.value
    if (currentLyricVal) {
      // 寻找到当前时间的对应歌词
      currentLyricVal.seek(currentTime.value * 1000)
    }
  }
  // 停止歌词
  function stopLyric() {
    const currentLyricVal = currentLyric.value
    if (currentLyricVal) {
      // 寻找到当前时间的对应歌词
      currentLyricVal.stop()
    }
  }
  // 解析歌词(lineNum: lineNum歌词第几行,  txt当前时间行歌词文本)
  async function handleLyric({ lineNum, txt }) {
    playingLyric.value = txt
    // 获取当前行号
    currentLineNum.value = lineNum
    // dom获取
    const scrollComp = lyricScrollRef.value
    const listEl = lyricListRef.value
    // 没有歌曲列表(无dom节点)
    if (!listEl) {
      return false
    }
    // 保证歌曲播放到大于5行时候，当前播放的歌词依然在屏幕中间
    if (lineNum > 5) {
      // 相当于到 top: 0的位置
      const lineEl = listEl.children[lineNum - 5]
      scrollComp.scroll.scrollToElement(lineEl, 1000)
    } else {
      // 小于5行则在头部滚动
      scrollComp.scroll.scrollTo(0, 0, 1000)
    }
  }
  return {
    currentLyric,
    currentLineNum,
    pureMusicLyric,
    playingLyric,
    lyricScrollRef,
    lyricListRef,
    playLyric,
    stopLyric
  }
}
